//
// test.go
// Copyright (C) 2019 crane <crane@his-pc>
//
// Distributed under terms of the MIT license.
//

package main

import (
	"fmt"
	"runtime"
	// "os"
	"sync"
)

// NOTE: BUG没找到, 有时候得出199999, 199997
var (
	turn       int
	interested [2]bool
)

func em() {

}

func enterRegion(process int) {
	// fmt.Println("loop tryenter ", process)
	other := 1 - process
	interested[process] = true

	//turn = process
	turn = other

	// for turn == process && interested[other] == true {
	for turn == other && interested[other] == true {
		runtime.Gosched()
	}
}

func leaveRegion(process int) {
	interested[process] = false
}

func test() {
	wg := sync.WaitGroup{}

	cnt := 0
	//total := 10000
	total := 1000000

	wg.Add(2)

	runc := func(processid int, total int) {
		defer wg.Done()
		inner := 0
		for i := 0; i < total; i++ {
			enterRegion(processid)
			//cnt += 1
			cnt++ // critical section
			leaveRegion(processid)
			inner += 1
		}
		fmt.Println("inner is ", inner, processid)
	}

	for work := 0; work < 2; work++ {
		fmt.Println("work ", work)
		go runc(work, total)
	}

	wg.Wait()
	fmt.Println("cnt is ", cnt)
}

func main() {
	runtime.GOMAXPROCS(1)
	fmt.Println("start main")
	test()
}
